#pragma once


#include <string>
#include <queue>
#include <sstream>
#include <fstream>
#include <exl.h>


class LogWriter : public exl::ps::ThreadBase
{
	std::string logFileName;
	
	std::queue <std::string> messages;
	std::ostringstream msgline;
	
	bool started;

	inline void startIfNecessary()
	{
		if (!started)
		{
			this->start();
			//while (!this->isRunning()) Sleep(1);
		}
	}

public:
	LogWriter(const std::string & logFileName)
		: logFileName(logFileName), started(false)
	{ }


	template <class T>
	std::ostream & operator << (T v)
	{
		startIfNecessary();
		synchronized (this)
		{
			return msgline << v;
		}
	}

	void flush()
	{
		startIfNecessary();
		synchronized (this)
		{
			const std::string msg = msgline.str();
			messages.push(msg);
			msgline.str("");
		}
	}


	int run()
	{
		started = true;

		std::ofstream of(logFileName.c_str());

		while (!mustTerminate())
		{
			if (!messages.empty())
			{
				std::string & msg = messages.front();

				of << msg;
				of.flush();

				synchronized (this)
				{
					messages.pop();
				}
			}
		}

		of.close();

		return 0;
	}
};
